//
//  CXOAuthController.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/19.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit
import SVProgressHUD

/// APP Key
let CXWB_CLIENT_ID = "2000044582"
/// 回调页的URL
let CXWB_REDIRECT_ID = "http://www.baidu.com/"
let CXWB_CLIENT_SECRET = "9e1b87f78101d446f35ebf1b1e760f3b"

class CXOAuthController: UIViewController {
    
    private lazy var wv:UIWebView = {
        let wv = UIWebView()
        wv.delegate = self
        return wv
    }()
    
///  将view替换成webview
    override func loadView() {
        view = wv
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        setupPageByGet()
    }
    
    func setupUI() {
        navigationItem.title = "新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFill")
    }
///  GET 请求
    private func setupPageByGet() {
        
        let request = NSURLRequest(URL: NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(CXWB_CLIENT_ID)&redirect_uri=\(CXWB_REDIRECT_ID)")!)
        wv.loadRequest(request)
    }
}
// MARK: - 加载请求页的代理监听
extension CXOAuthController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView:UIWebView) {
        //进度条开始运转
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        //进度条停止运转
        SVProgressHUD.dismiss()
    }
    //要求页面不加载回调页 获取授权码等信息
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //每一次页面加载都会调用该代理方法，因此需要判断URL是否为nil
        guard let url = request.URL else {
            return false
        }
        let urlStr = url.absoluteString
        //URL存在，但是不是指定的回调页
        if !urlStr.hasPrefix(CXWB_REDIRECT_ID) {
            return true
        }
        let query = url.query! //该属性返回URL中问号之后的字符串
        if !query.hasPrefix("code=") {
            return true
        }
        /// 获取code，然后去申请获得access token.之后取得用户信息
        let code = query.substringFromIndex("ccccc".endIndex)
        print("获取的授权码是: \(code)")
        
        //把请求网络这一步交给ViewModel去完成
        CXUserInfoViewModel.sharedUserModel.loadUserInfo(code) { (isSuccess) -> Void in
            if isSuccess {
                //获取用户信息成功，进行页面跳转 将当前授权页释放
                print("获取用户信息完毕,回到了授权页")
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        //object: 通知的发布者
                        //把切换控制器界面的工作交给UIApplicationDelegate
                        NSNotificationCenter.defaultCenter().postNotificationName(CXSwitchRootVCNotification, object: self)
                })
                SVProgressHUD.dismiss()
            } else {
                SVProgressHUD.showErrorWithStatus("获取用户信息失败")
            }
        }
        return false
    }
}
// MARK: - 导航条上的按钮点击
extension CXOAuthController {
    
    @objc private func cancelClick() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func autoFill() {
        //执行JS代码
        let jsexec = "document.getElementById('userId').value='409304110@qq.com';document.getElementById('passwd').value='chuanshuo085'"
        wv.stringByEvaluatingJavaScriptFromString(jsexec)
    }
}
